package com.wushi.lenovo.asia5b.app_ui.good.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mvp.base.BaseMvpActivity;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.OrderCheckPiActivityView;
import com.wushi.lenovo.asia5b.app_di.goods.presenter.OrderCheckPiActivityPresenter;
import com.wushi.lenovo.asia5b.app_event.ChangeAddressEvent;
import com.wushi.lenovo.asia5b.app_event.FacebookEvent;
import com.wushi.lenovo.asia5b.app_event.NewAddressEvent;
import com.wushi.lenovo.asia5b.app_event.OrderPayEvent;
import com.wushi.lenovo.asia5b.app_event.SelectVoucherEvent;
import com.wushi.lenovo.asia5b.app_model.credit.bean.TopupInfoBean;
import com.wushi.lenovo.asia5b.app_model.good.ChargesBean;
import com.wushi.lenovo.asia5b.app_model.good.DeliveriesBean;
import com.wushi.lenovo.asia5b.app_model.good.OrderPayPriceModel;
import com.wushi.lenovo.asia5b.app_model.good.PaymentMethodModel;
import com.wushi.lenovo.asia5b.app_model.good.ShopModel;
import com.wushi.lenovo.asia5b.app_model.good.bean.StepHelper;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.GoodsModel;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_model.profile.AddressModel;
import com.wushi.lenovo.asia5b.app_model.voucher.VoucherModel;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.OrderCheckPriceAdapter;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.OrderPaymentMethodAdapter;
import com.wushi.lenovo.asia5b.app_ui.good.view.OrderAddressView;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.OrderKouzhaoDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.SelectVoucherDialogFragment;
import com.wushi.lenovo.asia5b.app_ui.pay.activity.PayActivity;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.ChangeAddressActivity;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.NewAddressActivity;
import com.wushi.lenovo.asia5b.app_ui.shopcar.adapter.OrderCheckPiShopAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

/**
 * Created by zhangyuncai on 2019/10/31.
 * 自营商品付款 todo 因为是自营商品,所以没有本地派送方式
 * 代购商品付款 todo 因为第一次付款,所以没有国际派送和本地派送
 */
public class OrderCheckPiActivity extends BaseMvpActivity<OrderCheckPiActivityView, OrderCheckPiActivityPresenter> implements OrderCheckPiActivityView {

    @BindView(R.id.view_ordercheck_empty)
    View view_ordercheck_empty;
    //商品列表
    @BindView(R.id.rv_ordercheck_goods)
    RecyclerView rv_ordercheck_goods;
    @BindView(R.id.tv_order_uservoucher)
    TextView tv_order_uservoucher;
    @BindView(R.id.tv_ordercheck_uservoucherlist)
    TextView tv_ordercheck_uservoucherlist;
    @BindView(R.id.tv_ordercheck_uservoucherlist2)
    TextView tv_ordercheck_uservoucherlist2;
    @BindView(R.id.et_ordercheck_voucherno)
    EditText et_ordercheck_voucherno;
    @BindView(R.id.et_ordercheck_apply)
    TextView et_ordercheck_apply;
    @BindView(R.id.ll_ordercheck_voucher_vessel)
    LinearLayout ll_ordercheck_voucher_vessel;
    @BindView(R.id.ll_ordercheck_voucher_allvessel)
    LinearLayout ll_ordercheck_voucher_allvessel;
    @BindView(R.id.tv_ordercheck_totalprice)
    TextView tv_ordercheck_totalprice;
    @BindView(R.id.cb_ordercheck_insurance)
    CheckBox cb_ordercheck_insurance;
    @BindView(R.id.bt_ordercheck_submit)
    Button bt_ordercheck_submit;
    @BindView(R.id.ll_ordercheck_bottom)
    LinearLayout ll_ordercheck_bottom;
    @BindView(R.id.bt_order_newaddres)
    Button bt_order_newaddres;
    @BindView(R.id.ll_order_newaddres_vessel)
    LinearLayout ll_order_newaddres_vessel;
    //国际派送
    @BindView(R.id.rv_ordercheck_internationalmethod)
    RecyclerView internationalRecyclerView;
    @BindView(R.id.ll_ordercheck_internationalmethod_vessel)
    LinearLayout ll_ordercheck_internationalmethod_vessel;
    //支付方式
    @BindView(R.id.rv_ordercheck_paymentmethos)
    RecyclerView paymentRecyclerView;
    //商品价格详情
    @BindView(R.id.rv_order_pricedetail)
    RecyclerView pricedetailRecyclerView;
    @BindView(R.id.tv_ordercheck_notice)
    TextView tv_ordercheck_notice;
    @BindView(R.id.iv_ordercheck_info)
    ImageView iv_ordercheck_info;
    @BindView(R.id.tv_ordercheck_address)
    TextView tv_ordercheck_address;
    @BindView(R.id.tv_ordercheck_intermethod)
    TextView tv_ordercheck_intermethod;
    @BindView(R.id.tv_ordercheck_paymentmethos)
    TextView tv_ordercheck_paymentmethos;
    @BindView(R.id.address_ordercheck)
    OrderAddressView address_ordercheck;
    @BindView(R.id.iv_ordercheck_info2)
    ImageView iv_ordercheck_info2;
    //收货地址
    private AddressModel addressModel;
    //选择优惠券
    private VoucherModel selectVoucherModel;
    //是否是代购商品
    private boolean isDaigouGoods = false;
    //价格详细
    private OrderPayPriceModel orderPayPriceModel;

    private final MapHelper extraMap = MapHelper.newHashMap();
    private OrderCheckPiShopAdapter orderCheckPiShopAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ordercheckpi;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        List<Integer> idList = (List<Integer>) getIntent().getSerializableExtra("datas");
        isDaigouGoods = getIntent().getBooleanExtra("isDaigouGoods", false);
        getPresenter().isDaigouGoods = isDaigouGoods;
        if (isDaigouGoods) {
            Timber.d("--->>>>>>>>---代购商品第一次付款");
        } else {
            Timber.d("--->>>>>>>>---自营商品付款");
        }
        getPresenter().addGoods(idList);
        if (idList == null || idList.size() <= 0) {
            return;
        }
        initView();

        initData();

        initEvent();
    }

    /**
     * 初始化视图
     */
    @Override
    protected void initView() {
        //设置下划线
        tv_order_uservoucher.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tv_ordercheck_uservoucherlist.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线


        EyeUtils.setLinkText(mActivity, getString(R.string.shopcar_pi_notice), getString(R.string.shopcar_pi_notice_key),
                tv_ordercheck_notice, WebUrlType.shopcar_pi);


        //步骤1/2/3
        int index = 0;
        if (isDaigouGoods) {//代购
            tv_ordercheck_address.setText(StepHelper.getStep(getString(R.string.billingaddress), index++));
            tv_ordercheck_paymentmethos.setText(StepHelper.getStep(getString(R.string.paymentmethod), index++));
        } else {
            tv_ordercheck_address.setText(StepHelper.getStep(getString(R.string.shippingaddress), index++));
            tv_ordercheck_intermethod.setText(StepHelper.getStep(getString(R.string.internationalshippingmethod), index++));
            tv_ordercheck_paymentmethos.setText(StepHelper.getStep(getString(R.string.paymentmethod), index++));
        }
//            <string name="orderpayment_step_paytype">%s付款方式</string>
//            <string name="orderpayment_step_paytype">%sPayment Method</string>

        //是否有国际派送
        ll_ordercheck_internationalmethod_vessel.setVisibility(isDaigouGoods ? View.GONE : View.VISIBLE);
        //是否显示优惠券
        if (isDaigouGoods) {
            tv_ordercheck_uservoucherlist2.setVisibility(View.GONE);
        } else {
            tv_ordercheck_uservoucherlist2.setVisibility(View.VISIBLE);
        }
    }

    protected void setGoodsView(List<ShopModel> shopModels) {
        /**
         * 显示商品列表
         */
        if (orderCheckPiShopAdapter == null && shopModels != null) {
            orderCheckPiShopAdapter = new OrderCheckPiShopAdapter(shopModels);
            orderCheckPiShopAdapter.isDaigouGoods = isDaigouGoods;
            rv_ordercheck_goods.setLayoutManager(new LinearLayoutManager(mActivity));
            rv_ordercheck_goods.setAdapter(orderCheckPiShopAdapter);

            if (!isDaigouGoods) {
                for (ShopModel shopModel : shopModels) {
                    if (shopModel.products != null) {
                        for (GoodsModel goodsModel : shopModel.products) {
                            if (goodsModel.isMingan()) {
                                iv_ordercheck_info.setVisibility(View.VISIBLE);
                                break;
                            }
                        }
                    }
                }
            }

        }
    }

    /**
     * 显示优惠券列表
     */
    private void showSelectVoucherDialog() {
        SelectVoucherDialogFragment selectVoucherDialogFragment = new SelectVoucherDialogFragment();
        selectVoucherDialogFragment.show(getSupportFragmentManager(), getLocalClassName());
    }

    /**
     * 设置国际运输方式
     *
     * @param deliveries
     */
    public void setInternationalDeliveryView(List<DeliveriesBean> deliveries) {
        OrderPaymentMethodAdapter internationalAdapter = new OrderPaymentMethodAdapter(deliveries == null ? new ArrayList() : deliveries);
        internationalRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        internationalRecyclerView.setAdapter(internationalAdapter);
        internationalAdapter.setOnItemClickListener((adapter, view, position) -> {
            DeliveriesBean bean = (DeliveriesBean) internationalAdapter.getItem(position);
            if (internationalAdapter.getSelectPosition() != position) {
                extraMap.put("international_delivery_method", bean.getCode());
                getCharges();//①
            }
            internationalAdapter.setSelectPosition(position);
        });
    }

    /**
     * 设置支付方式
     *
     * @param payments
     */
    public void setPaymentMethodView(List<PaymentMethodModel.PaymentsBean> payments) {
        OrderPaymentMethodAdapter paymentAdapter = new OrderPaymentMethodAdapter(payments == null ? new ArrayList() : payments);
        paymentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        paymentRecyclerView.setAdapter(paymentAdapter);
        paymentAdapter.setOnItemClickListener((adapter, view, position) -> {
            PaymentMethodModel.PaymentsBean bean = (PaymentMethodModel.PaymentsBean) paymentAdapter.getItem(position);
            if (paymentAdapter.getSelectPosition() != position) {
                extraMap.put("payment_method", bean.getCode());
                getCharges();//③
            }
            paymentAdapter.setSelectPosition(position);
        });
    }

    /**
     * 选择优惠券
     *
     * @param selectVoucherModel
     */
    private void setSelectVoucherModel(VoucherModel selectVoucherModel) {
        this.selectVoucherModel = selectVoucherModel;
        getCharges();//⑤
    }

    /**
     * 设置价格详细
     *
     * @param orderPayPriceModel
     */
    private void setPriceDetailView(OrderPayPriceModel orderPayPriceModel) {
        this.orderPayPriceModel = orderPayPriceModel;
        if (orderPayPriceModel != null) {
            tv_ordercheck_totalprice.setText(orderPayPriceModel.getTotal_text());
            List<ChargesBean> charges = orderPayPriceModel.getCharges();
            if (orderPayPriceModel != null && charges != null) {
                Iterator<ChargesBean> iterator = charges.iterator();
                while (iterator.hasNext()) {
                    /**
                     * 因为视图分离,所以移除了这个
                     */
                    if (TextUtils.equals(iterator.next().getCode(), "total")) {
                        iterator.remove();
                    }
                }
                pricedetailRecyclerView.setLayoutManager(new LinearLayoutManager(this));
                OrderCheckPriceAdapter priceAdapter = new OrderCheckPriceAdapter(charges);
                pricedetailRecyclerView.setAdapter(priceAdapter);
                priceAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                    @Override
                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                        if (view.getId() == R.id.tv_ordercheck_remove) {//移除优惠券
                            setSelectVoucherModel(null);
                        }
                    }
                });
            }

            setGoodsView(orderPayPriceModel.shops);
        } else {
            tv_ordercheck_totalprice.setText("-");
            pricedetailRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            OrderCheckPriceAdapter priceAdapter = new OrderCheckPriceAdapter(new ArrayList<>());
            pricedetailRecyclerView.setAdapter(priceAdapter);
        }
        bt_ordercheck_submit.setEnabled(orderPayPriceModel != null);

    }


    @Override
    protected void initData() {
        getCharges();
    }

    /**
     * 获取商品列表价格
     * ①派送方式变化时
     * ②支付方式变化时
     * ③保险复选框变化时
     * ④优惠券变化时
     */
    private void getCharges() {
        extraMap.put("insurance", cb_ordercheck_insurance.isChecked() ? "1" : "null");
        extraMap.put("voucher", selectVoucherModel == null ? "null" : selectVoucherModel.getVoucher_code() + "");
        extraMap.put("local_delivery_method", "");
        if (isDaigouGoods) {
            extraMap.put("international_delivery_method", "");
        }
        getPresenter().getCharges(extraMap);
    }


    @Override
    protected void initEvent() {
        iv_ordercheck_info2.setOnClickListener(v -> {
            new OrderKouzhaoDialog(mActivity).show();
        });
        /**
         * 保险复选框
         */
        cb_ordercheck_insurance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                getCharges();//⑥
            }
        });
    }

    @OnClick({
            R.id.view_ordercheck_empty,
            R.id.tv_order_edit,
            R.id.tv_order_uservoucher,
            R.id.tv_ordercheck_uservoucherlist,
            R.id.tv_ordercheck_uservoucherlist2,
            R.id.et_ordercheck_apply,
            R.id.bt_ordercheck_submit,
            R.id.bt_order_newaddres,
            R.id.iv_ordercheck_info
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             * 防止点击穿透到下层
             */
            case R.id.view_ordercheck_empty:
                break;
            case R.id.iv_ordercheck_info: {
                ToastUtil.showToast(getString(R.string.orderpayment_mingantishi));
                break;
            }
            /**
             * 修改地址
             */
            case R.id.tv_order_edit: {
                startActivity(new Intent(this, ChangeAddressActivity.class));
            }
            break;
            /**
             * 新建地址
             */
            case R.id.bt_order_newaddres: {
                Intent intent = new Intent(this, NewAddressActivity.class);
                intent.putExtra("OrderPayment", true);
                startActivity(intent);
            }
            break;
            /**
             * 显隐优惠券输入框
             */
            case R.id.tv_order_uservoucher: {
                int visibility = ll_ordercheck_voucher_vessel.getVisibility();
                ll_ordercheck_voucher_vessel.setVisibility(visibility == View.GONE ? View.VISIBLE : View.GONE);
            }
            break;
            /**
             * 显示优惠券列表
             */
            case R.id.tv_ordercheck_uservoucherlist2:
            case R.id.tv_ordercheck_uservoucherlist: {
                showSelectVoucherDialog();
            }
            break;
            /**
             * 验证优惠券
             */
            case R.id.et_ordercheck_apply: {
                String voucherCode = et_ordercheck_voucherno.getText().toString().trim();
                getPresenter().validateVoucher(voucherCode, orderPayPriceModel);
            }
            break;
            /**
             * 支付
             */
            case R.id.bt_ordercheck_submit: {
                if (addressModel == null) {
                    if (isDaigouGoods) {
                        ToastUtil.showToast(getString(R.string.orderpayment_fillup_address_billing));
                    } else {
                        ToastUtil.showToast(getString(R.string.orderpayment_fillup_address_delivery));
                    }
                    return;
                }
                if (orderPayPriceModel != null && orderPayPriceModel.getExtra_data() != null && !TextUtils.isEmpty(orderPayPriceModel.getExtra_data().payment_method)) {
                    String payCode = orderPayPriceModel.getExtra_data().payment_method;
                    //支付方式
                    TopupInfoBean topupInfoBean = new TopupInfoBean();
                    topupInfoBean.OrderPaymentType = TopupInfoBean.OrderPaymentType_fist;
                    if (isDaigouGoods) {
                        topupInfoBean.goodsType = 1;
                    } else {
                        topupInfoBean.goodsType = 2;
                    }
                    topupInfoBean.setCheckout_log_id(orderPayPriceModel.getCheckout_log_id());
                    String total = orderPayPriceModel.getTotal();
                    topupInfoBean.setTotalAmount(total);
                    Intent intent = new Intent(mActivity, PayActivity.class);
                    intent.putExtra(CommonConstant.TopupInfoBean, topupInfoBean);
                    intent.putExtra("payCode", payCode);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast("payCode is error!");
                }

            }
            break;
            default:
                break;
        }

    }

    /**
     * 获取价格详细回调
     *
     * @param orderPayPriceModel
     */
    @Override
    public void getChargesResult(OrderPayPriceModel orderPayPriceModel) {
        view_ordercheck_empty.setVisibility(View.GONE);
        setPriceDetailView(orderPayPriceModel);
    }


    /**
     * 此时在UI线程
     *
     * @param addressModel
     */
    @Override
    public void getAddressModelResult(AddressModel addressModel) {
        this.addressModel = addressModel;
        address_ordercheck.setAddressView(addressModel);
    }

    @Override
    public void getInternationalDeliveryMethodResult(List<DeliveriesBean> deliveries) {
        setInternationalDeliveryView(deliveries);
    }

    @Override
    public void getPaymentMethodsResult(List<PaymentMethodModel.PaymentsBean> paymentsBeans) {
        setPaymentMethodView(paymentsBeans);
    }

    @Override
    public void validateVoucherResult(VoucherModel voucherModel) {
        setSelectVoucherModel(voucherModel);
    }

    /**
     * 地址改动通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onChangeAddress(ChangeAddressEvent event) {
        if (event != null && event.addressModel != null) {
            this.addressModel = event.addressModel;
            address_ordercheck.setAddressView(addressModel);
            extraMap.clear();
            getPresenter().addressModel = addressModel;
            getCharges();
        }


    }

    /**
     * 新建地址通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onNewAddressEvent(NewAddressEvent event) {
        if (event != null) {
            if (addressModel == null) {
                extraMap.clear();
                getCharges();
            }
        }


    }

    /**
     * 支付后通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onOrderPayEventEvent(OrderPayEvent event) {

        if (event != null) {
            if (event.resultModel.isSuccess()) {
                if (orderPayPriceModel != null) {
                    FacebookEvent.Companion.ordetPayment(orderPayPriceModel.getTotal());
                }
                finish();
            } else {//支付失败后,重新加载数据
                getCharges();
            }
        }

    }

    /**
     * 选择优惠券
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onSelectVoucherEvent(SelectVoucherEvent event) {

        if (event != null) {
            setSelectVoucherModel((VoucherModel) event.serializable);
        }

    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        super.dismissLoadingBar(dississTag);
        view_ordercheck_empty.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
